package com.mlnx.bluwifi.tp;


import com.mlnx.bluwifi.utils.ByteBuffUtils;

import java.nio.ByteBuffer;


/**
 * Created by Administrator on 2019/3/6 0006.
 */

public class BerrySpoPacket implements Packet{
    private SpoLis spoLis;
    private ByteBuffer packetBuff;
    private State state = State.HEAD;
    private OxiParams mOxiParams = new OxiParams();

    enum State {
        HEAD, CONTANT
    }

    public BerrySpoPacket(SpoLis spoLis) {
        this.spoLis = spoLis;
        packetBuff = ByteBuffer.allocate(500);
        packetBuff.flip();
    }

    @Override
    public void decode(byte[] bytes, int len) {
        int dat = 0;
        int[] packageData;
        ByteBuffUtils.addBytes(packetBuff, bytes, len);
        while (true) {
            switch (state) {
                case HEAD:
                    if (packetBuff.remaining() > 0) {
                        dat = toUnsignedInt(packetBuff.get());
                        if ((dat & 0x80) > 0) {
                            state = State.CONTANT;
                        } else {
                            return;
                        }
                    } else {
                        return;
                    }
                case CONTANT:
                    if (packetBuff.remaining() >= 4) {
                        packageData = new int[5];
                        packageData[0] = dat;
                        for (int i = 1; i < packageData.length; i++) {
                            dat = toUnsignedInt(packetBuff.get());
                            if ((dat & 0x80) == 0) {
                                packageData[i] = dat;
                            } else {
                                continue;
                            }
                        }
                        proceePacket(packageData);
                    }
            }
            state = State.HEAD;
        }
    }

    private void proceePacket(int[] packageData) {
        int spo2 = packageData[4];
        int pulseRate = packageData[3] | ((packageData[2] & 0x40) << 1);
        int pi = packageData[0] & 0x0f;
        if (spoLis != null) {
            spoLis.spo(spo2, pulseRate, pi);
            spoLis.onPlethWaveReceived(packageData[1]);
        }
    }


    private int toUnsignedInt(byte x) {
        return ((int) x) & 0xff;
    }


    public class OxiParams {
        private int spo2;
        private int pulseRate;
        private int pi;             //perfusion index

        private void update(int spo2, int pulseRate, int pi) {
            this.spo2 = spo2;
            this.pulseRate = pulseRate;
            this.pi = pi;
        }

        public int getSpo2() {
            return spo2;
        }

        public int getPulseRate() {
            return pulseRate;
        }

        public int getPi() {
            return pi;
        }
    }

    public interface SpoLis {
        void spo(int spo, int pulse, int pi);

        default void onPlethWaveReceived(int amp){}
    }
}
